package com.cdwm.mrp.common.tools;

import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;

import java.io.*;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

/**
 * @version v1.0
 * @Author: lyw
 * @Date: 2021/8/20
 */
public class PdfUtil {
    /**
     * 本地文件word转pdf
     * @param wordFilePath word文件路径
     * @param pdfFilePath  pdf文件路径
     * @param suffix  文件后缀
     * @return 成功或失败
     */
    public static boolean doc2Pdf(File wordFilePath, File pdfFilePath, String suffix) {
        boolean result = false;
        try {
            InputStream inputStream = new FileInputStream(wordFilePath);
            OutputStream outputStream = new FileOutputStream(pdfFilePath);


            ArrayList<String> systemRoot = UploadPathUtil.getSystemRoot();

            IConverter converter = LocalConverter.builder().baseFolder(new File(systemRoot.get(0)))
                    .workerPool(20,25,1, TimeUnit.SECONDS)
                    .processTimeout(5,TimeUnit.SECONDS)
                    .build();

            // 工具后缀进行转换
            if(suffix.equals(".doc")){
                converter.convert(inputStream).as(DocumentType.DOC).to(outputStream).as(DocumentType.PDF).execute();
            } else if(suffix.equals(".docx")){
                converter.convert(inputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
            } else if(suffix.equals(".txt")){
                converter.convert(inputStream).as(DocumentType.TEXT).to(outputStream).as(DocumentType.PDF).execute();
            }
            outputStream.close();
            result = true;
        } catch (Exception e) {

            e.printStackTrace();
        }
        return result;
    }
}
